/**
 * 医院突发事件系统
 * 用于模拟和处理医院内的突发事件，并在3D地图上显示
 */

import { timeUtils } from './realData'
import { nanoid } from 'nanoid'

// 突发事件类型
export enum EmergencyType {
  FIRE = 'fire',                 // 火灾
  MEDICAL = 'medical',           // 医疗紧急情况
  SECURITY = 'security',         // 安全事件
  INFRASTRUCTURE = 'infrastructure', // 基础设施故障
  CROWD = 'crowd',               // 人群聚集
  EXTERNAL = 'external'          // 外部事件影响
}

// 突发事件严重程度
export enum EmergencySeverity {
  CRITICAL = 'critical',   // 危急 - 需要立即疏散或全院响应
  HIGH = 'high',           // 高危 - 需要紧急响应团队
  MEDIUM = 'medium',       // 中度 - 需要相关部门处理
  LOW = 'low'              // 低危 - 需要记录和监控
}

// 突发事件状态
export enum EmergencyStatus {
  ACTIVE = 'active',           // 活跃中
  RESPONDING = 'responding',   // 正在响应
  CONTAINED = 'contained',     // 已控制
  RESOLVED = 'resolved'        // 已解决
}

// 突发事件接口
export interface EmergencyEvent {
  id: string;
  type: EmergencyType;
  title: string;
  description: string;
  location: {
    name: string;           // 位置名称
    floor: string;          // 楼层
    coordinates: [number, number]; // 经纬度坐标
    areaRadius?: number;    // 影响半径(米)
  };
  severity: EmergencySeverity;
  status: EmergencyStatus;
  startTime: string;        // ISO时间字符串
  estimatedEndTime?: string; // 预计结束时间
  respondingTeams?: string[]; // 响应团队
  affectedDepartments?: string[]; // 受影响部门
  evacuationRequired: boolean; // 是否需要疏散
  updates: EmergencyUpdate[]; // 事件更新记录
  visualEffect?: {
    color: string;          // 显示颜色
    pulseRate?: number;     // 脉冲频率(秒)
    icon?: string;          // 图标名称
    scale?: number;         // 显示比例
  }
}

// 突发事件更新记录
export interface EmergencyUpdate {
  id: string;
  timestamp: string;
  content: string;
  updatedBy: string;
  statusChange?: EmergencyStatus;
}

// 预设的突发事件模板
export const emergencyTemplates = {
  fire: {
    type: EmergencyType.FIRE,
    title: '火灾警报',
    description: '检测到火灾警报，请按照疏散路线有序撤离',
    severity: EmergencySeverity.CRITICAL,
    evacuationRequired: true,
    visualEffect: {
      color: '#FF4500',
      pulseRate: 0.5,
      icon: 'fire',
      scale: 1.5
    }
  },
  medicalEmergency: {
    type: EmergencyType.MEDICAL,
    title: '医疗紧急情况',
    description: '需要紧急医疗响应团队',
    severity: EmergencySeverity.HIGH,
    evacuationRequired: false,
    visualEffect: {
      color: '#FF0000',
      pulseRate: 0.8,
      icon: 'medical',
      scale: 1.2
    }
  },
  securityBreach: {
    type: EmergencyType.SECURITY,
    title: '安全事件',
    description: '安全警报触发，安保人员正在处理',
    severity: EmergencySeverity.HIGH,
    evacuationRequired: false,
    visualEffect: {
      color: '#FFA500',
      pulseRate: 1,
      icon: 'security',
      scale: 1.2
    }
  },
  powerOutage: {
    type: EmergencyType.INFRASTRUCTURE,
    title: '电力故障',
    description: '部分区域电力供应中断，备用系统已启动',
    severity: EmergencySeverity.MEDIUM,
    evacuationRequired: false,
    visualEffect: {
      color: '#FFD700',
      pulseRate: 1.5,
      icon: 'power',
      scale: 1
    }
  },
  waterLeak: {
    type: EmergencyType.INFRASTRUCTURE,
    title: '水管泄漏',
    description: '检测到水管泄漏，维修人员正在处理',
    severity: EmergencySeverity.MEDIUM,
    evacuationRequired: false,
    visualEffect: {
      color: '#1E90FF',
      pulseRate: 2,
      icon: 'water',
      scale: 1
    }
  },
  crowdGathering: {
    type: EmergencyType.CROWD,
    title: '人群聚集',
    description: '区域人员密度过高，请避免前往',
    severity: EmergencySeverity.LOW,
    evacuationRequired: false,
    visualEffect: {
      color: '#9370DB',
      pulseRate: 3,
      icon: 'crowd',
      scale: 1
    }
  },
  externalDisaster: {
    type: EmergencyType.EXTERNAL,
    title: '外部灾害警报',
    description: '收到外部灾害警报，请关注后续通知',
    severity: EmergencySeverity.HIGH,
    evacuationRequired: false,
    visualEffect: {
      color: '#8B0000',
      pulseRate: 1,
      icon: 'warning',
      scale: 1.3
    }
  }
}

// 突发事件服务
class EmergencyService {
  private activeEmergencies: EmergencyEvent[] = [];
  private historicalEmergencies: EmergencyEvent[] = [];
  private listeners: ((events: EmergencyEvent[]) => void)[] = [];
  
  // 创建新的突发事件
  createEmergency(
    template: keyof typeof emergencyTemplates,
    location: { name: string; floor: string; coordinates: [number, number]; areaRadius?: number },
    customDetails?: Partial<EmergencyEvent>
  ): EmergencyEvent {
    const baseTemplate = emergencyTemplates[template];
    const now = new Date();
    
    const emergency: EmergencyEvent = {
      id: `EM-${nanoid(6)}`,
      type: baseTemplate.type,
      title: customDetails?.title || baseTemplate.title,
      description: customDetails?.description || baseTemplate.description,
      location,
      severity: customDetails?.severity || baseTemplate.severity,
      status: EmergencyStatus.ACTIVE,
      startTime: now.toISOString(),
      evacuationRequired: customDetails?.evacuationRequired ?? baseTemplate.evacuationRequired,
      updates: [{
        id: nanoid(8),
        timestamp: now.toISOString(),
        content: '事件初始报告',
        updatedBy: '系统',
      }],
      visualEffect: customDetails?.visualEffect || baseTemplate.visualEffect,
      ...customDetails
    };
    
    this.activeEmergencies.push(emergency);
    this.notifyListeners();
    return emergency;
  }
  
  // 更新突发事件
  updateEmergency(id: string, update: Partial<EmergencyEvent>, updateMessage?: string): EmergencyEvent | null {
    const index = this.activeEmergencies.findIndex(e => e.id === id);
    if (index === -1) return null;
    
    const emergency = this.activeEmergencies[index];
    const updatedEmergency = { ...emergency, ...update };
    
    // 添加更新记录
    if (updateMessage) {
      updatedEmergency.updates.push({
        id: nanoid(8),
        timestamp: new Date().toISOString(),
        content: updateMessage,
        updatedBy: '系统',
        statusChange: update.status
      });
    }
    
    this.activeEmergencies[index] = updatedEmergency;
    
    // 如果状态改为已解决，移至历史记录
    if (update.status === EmergencyStatus.RESOLVED) {
      this.activeEmergencies.splice(index, 1);
      this.historicalEmergencies.push(updatedEmergency);
    }
    
    this.notifyListeners();
    return updatedEmergency;
  }
  
  // 获取所有活跃的突发事件
  getActiveEmergencies(): EmergencyEvent[] {
    return [...this.activeEmergencies];
  }
  
  // 获取历史突发事件
  getHistoricalEmergencies(): EmergencyEvent[] {
    return [...this.historicalEmergencies];
  }
  
  // 根据ID获取突发事件
  getEmergencyById(id: string): EmergencyEvent | null {
    return this.activeEmergencies.find(e => e.id === id) || 
           this.historicalEmergencies.find(e => e.id === id) ||
           null;
  }
  
  // 添加监听器
  addListener(callback: (events: EmergencyEvent[]) => void): () => void {
    this.listeners.push(callback);
    return () => {
      this.listeners = this.listeners.filter(cb => cb !== callback);
    };
  }
  
  // 通知所有监听器
  private notifyListeners(): void {
    this.listeners.forEach(callback => callback(this.activeEmergencies));
  }
  
  // 生成随机突发事件（用于演示）
  generateRandomEmergency(hospitalData: any): EmergencyEvent | null {
    if (!hospitalData || !hospitalData.departments || !hospitalData.departments.length) {
      return null;
    }
    
    // 随机选择一个部门作为事件地点
    const department = hospitalData.departments[Math.floor(Math.random() * hospitalData.departments.length)];
    
    // 随机选择一个事件模板
    const templateKeys = Object.keys(emergencyTemplates) as Array<keyof typeof emergencyTemplates>;
    const template = templateKeys[Math.floor(Math.random() * templateKeys.length)];
    
    // 生成随机坐标（基于中心点的偏移）
    const centerLat = 30.2741; // 假设的医院中心点
    const centerLng = 120.1551;
    const latOffset = (Math.random() - 0.5) * 0.002; // 约±100米
    const lngOffset = (Math.random() - 0.5) * 0.002;
    
    return this.createEmergency(
      template,
      {
        name: department.name,
        floor: department.floor,
        coordinates: [centerLng + lngOffset, centerLat + latOffset],
        areaRadius: 20 + Math.random() * 30 // 20-50米的影响范围
      }
    );
  }
  
  // 模拟事件进展
  simulateEventProgression(): void {
    this.activeEmergencies.forEach(event => {
      const startTime = new Date(event.startTime).getTime();
      const now = Date.now();
      const elapsedMinutes = (now - startTime) / (1000 * 60);
      
      // 根据已经过去的时间更新事件状态
      if (elapsedMinutes > 30) {
        // 30分钟后，事件解决
        this.updateEmergency(event.id, 
          { status: EmergencyStatus.RESOLVED }, 
          '事件已解决，恢复正常运营'
        );
      } else if (elapsedMinutes > 15) {
        // 15分钟后，事件被控制
        if (event.status === EmergencyStatus.ACTIVE || event.status === EmergencyStatus.RESPONDING) {
          this.updateEmergency(event.id, 
            { status: EmergencyStatus.CONTAINED }, 
            '事件已被控制，正在恢复中'
          );
        }
      } else if (elapsedMinutes > 5) {
        // 5分钟后，开始响应
        if (event.status === EmergencyStatus.ACTIVE) {
          this.updateEmergency(event.id, 
            { status: EmergencyStatus.RESPONDING }, 
            '响应团队已到达现场，开始处理'
          );
        }
      }
    });
  }
}

export const emergencyService = new EmergencyService();